package com.hmdp.service.impl;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //校验用户手机号码
        if(RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号码不规范，请重新输入");
        }
        //生成6位数验证码
        String code = RandomUtil.randomNumbers(6);
        //存入session
//        session.setAttribute("code",code);
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //发送验证码到云服务商
        log.info("模拟验证码发送为：{}",code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //校验手机号，验证码
        String phone = loginForm.getPhone();
        String code = loginForm.getCode();
        //获取redis的验证码
        String trueCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        if(RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号码不规范，请重新输入");
        }
        if(trueCode != null && !trueCode.equals(code)){
            return Result.fail("验证码错误");
        }
        //根据手机号查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(User::getPhone,phone);
        User user = this.getOne(queryWrapper);
        //查询是否有当前手机号
        if(user == null){
            //不存在，创建用户
             user = createUser(loginForm);
        }
        //用户信息存入redis
        //生成随机唯一存储的key
        String token = UUID.randomUUID().toString(true);
        //存储内容脱敏
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //转化为map对象存储，方便多个字段一次性存储
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)  //忽略值为 null 的属性
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));  //将所有属性值转换为字符串。
        String tokenKey = LOGIN_USER_KEY+token;
        stringRedisTemplate.opsForHash().putAll(tokenKey,userMap);
        //设置有效期
        stringRedisTemplate.expire(tokenKey,LOGIN_USER_TTL,TimeUnit.MINUTES);
        return Result.ok(token);
    }

    @Override
    public Result logout(HttpServletRequest request) {
        //todo 包结构完善
        String token = request.getHeader("authorization");
        UserHolder.removeUser();
        String tokenKey = LOGIN_USER_KEY+token;
        stringRedisTemplate.opsForHash().delete(tokenKey);
        return Result.ok("退出登录成功");
    }


    @Override
    public Result sign() {
        //获取用户id
        Long userId = UserHolder.getUser().getId();
        //获取年月
        LocalDateTime now = LocalDateTime.now();
        //拼接key
        //日期规范化
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY + userId + keySuffix;
        //以用户id+年月为key,BitMap 为值去存储签到记录
        //获取今天是本月第几天
        int dayOfMonth = now.getDayOfMonth(); // 本月1-31
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth -1,true);  //true: 签到值为1
        return Result.ok();
    }

    @Override
    public Result signCount() {
        //获取用户id
        Long userId = UserHolder.getUser().getId();
        //获取年月
        LocalDateTime now = LocalDateTime.now();
        //拼接key
        //日期规范化
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY + userId + keySuffix;
        //以用户di+年月为key,BitMap 为值去存储签到记录
        //获取今天是本月第几天
        int dayOfMonth = now.getDayOfMonth(); // 本月1-31
        //获取到查询当天签到bitMap的字符串
        // 5.获取本月截止今天为止的所有的签到记录，返回的是一个十进制的数字 BITFIELD sign:5:202203 GET u14 0
        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0)
        );
        if(result == null || result.isEmpty()){
            return Result.ok(0); //没有签到，==签到0天
        }
        //签到标记
        Long num = result.get(0);
        if(num == null || num == 0){
            return Result.ok(0);
        }
        int count = 0;
        //处理返回结果，判断连续签到多少天
        while (true){
            if((num & 1) == 0){   //(num & 1) 的作用是提取 num 的最低位：0101 *1 =1
                //未签到
                break;
            }else{
                //不为0，表签到成功，连续签到次数➕1
                count ++;
            }
            // 把数字右移一位，抛弃最后一个bit位，继续下一个bit位
            num >>>= 1;
        }
        return Result.ok(count); //返回连续签到天数
    }

    private User createUser(LoginFormDTO loginForm) {
        User user = new User();
        user.setPhone(loginForm.getPhone());
        user.setNickName(USER_NICK_NAME_PREFIX +RandomUtil.randomNumbers(10));
        this.save(user);
        return user;
    }
}
